import { ref, reactive } from 'vue'
import app from '@/app'
import store from '@/app/store'
import goodsStore from './index'
import { count, countLog } from '@/api/store/goods'

// 初始化
const countStore = store()

// 分页
countStore.page = reactive({
  current: 1,
  pageSize: 0,
  total: 0,
  showPageSize: false,
  loading: false
})

countStore.get = () => {
  return new Promise((resolve, jeject) => {
    countStore.page.loading = true
    countLog(countStore.getData().id, countStore.getData()).then(res => {
      const list = res.data.map((item, index) => {
        item.id = index
        item.created_at = app.time.load(item.created_at)
        return item
      })
      countStore.setList(list)

      // 分页
      countStore.page.current = res.current_page
      countStore.page.pageSize = res.per_page
      countStore.page.total = res.total
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      countStore.page.loading = false
    })
  })
}

countStore.update = (data) => {
  return new Promise((resolve, jeject) => {
    count(countStore.getData().id, data).then(res => {
      countStore.get()
      goodsStore.get()
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 重置请求
countStore.reset = page => {
  countStore.page.current = page
  countStore.getData().page = page

  // 开始加载
  countStore.get()
}

// 商品id
countStore.id = id => {
  countStore.getData().id = id
}


export default countStore